import { getCartList, changeCount, delSelect } from '@/api/cart'
import { Toast } from 'vant'
export default {
  namespaced: true,
  state() {
    return {
      cartList: [],
    }
  },
  mutations: {
    setCartList(state, newList) {
      state.cartList = newList
    },
    setItemCheck(state, id) {
      const good = state.cartList.find(item => item.goods_id === id)
      good.isChecked = !good.isChecked
    },
    setAllCheck(state, flag) {
      state.cartList.forEach(item => item.isChecked = !flag)
    }
    , setCount(state, obj) {
      const good = state.cartList.find(item => item.goods_id == obj.goodsId)
      good.goods_num = obj.goodsNum
    }
  },
  actions: {
    async getCartAction(context) {
      const { data } = await getCartList()
      console.log(data.list);
      data.list.forEach(item => {
        item.isChecked = true
      })
      context.commit('setCartList', data.list)
    },
    async changeCountAction(context, obj) {
      const { goodsId, goodsNum, goodsSkuId } = obj
      context.commit('setCount', { goodsId, goodsNum })
      await changeCount(goodsId, goodsNum, goodsSkuId)
    },
    async delCartAction(context, obj) {
      const cartid = context.getters.selCartList.map(item => item.id)
      await delSelect(cartid)
      context.dispatch('getCartAction')
    }
  },

  getters: {
    cartTotal(state) {
      return state.cartList.reduce((sum, item) => sum + item.goods_num, 0)
    },
    selCartList(state) {
      return state.cartList.filter(item => item.isChecked)
    },
    selCount(state, getters) {
      return getters.selCartList.reduce((sum, item) => sum + item.goods_num, 0)
    },
    selPrice(state, getters) {
      return getters.selCartList.reduce((sum, item) => {
        return sum + item.goods_num * item.goods.goods_price_min
      }, 0).toFixed(2)
    },
    AllCheck(state) {
      return state.cartList.every(item => item.isChecked)
    }
  }
}